package com.xqyq.dao;


import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xqyq.model.User;


@Repository
public class UserDao {
	@Autowired
	protected SessionFactory sessionFactory;
	
	public int register(User user){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from User where mail=?");
		
		
		// 判断 是否 已经注册
		query.setString(0, user.getMail());
		if(query.uniqueResult()==null){
			return (Integer) session.save(user);
		}
		else{
			return 0;
		}
	}
	
	public User login(User user){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from User u where u.mail=? and u.password=?");
		query.setString(0, user.getMail());
		query.setString(1, user.getPassword());
		return (User) query.uniqueResult();
	}
	
	public User getUser(int user_id){
		Session session = sessionFactory.getCurrentSession();
		return (User) session.get(User.class, user_id);
	}

	public void update(User user){
		Session session = sessionFactory.getCurrentSession();
		session.update(user);
	}

	public User getUserByEmail(String email) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from User where mail=?");
		query.setString(0, email);
		return (User) query.uniqueResult();
	}
}
